<template>
  <div class="app-container">
    <uc-table url="admin/inChannelStorage/getPage" name="信道管理" ref="taskTable" pageable table-border :search-form="searchForm">
      <template slot="searchForm">
      </template>
      <template slot="columns">
        <el-table-column prop="channelId" label="信道Id" align="left" :show-overflow-tooltip="true"></el-table-column>
        <el-table-column prop="reprotPersonName" label="上报人" align="left" :show-overflow-tooltip="true"></el-table-column>
        <el-table-column prop="videoUrl" label="视频地址" align="left" :show-overflow-tooltip="true">
            <template slot-scope="scope">
                {{scope.row.videoUrl||"暂无链接"}}
            </template>
        </el-table-column>
        <el-table-column prop="startTime" label="开始时间" align="left" :show-overflow-tooltip="true">
            <template slot-scope="scope">
                {{scope.row.startTime|dateFormat}}
            </template>
        </el-table-column>
        <el-table-column prop="endTime" label="结束时间" align="left" :show-overflow-tooltip="true">
            <template slot-scope="scope">
                {{scope.row.endTime|dateFormatEnd}}
            </template>
        </el-table-column>
        <el-table-column prop="address" label="操作" width="110" align="left" class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <el-button size="mini" :disabled="scope.row.videoUrl==null" icon="el-icon-edit" type="primary" @click="handleVideo(scope.row)">查看视频</el-button>
<!--            <el-button size="mini" :disabled="scope.row.endTime!=null" type="danger" icon="el-icon-delete"  @click="enterVideo(scope.row)">加入频道</el-button>-->
          </template>
        </el-table-column>
      </template>
    </uc-table>

      <el-dialog title="信道视频" :visible.sync="videoDialogVisible" width="60%">
          <video :src="videoUrl"  controls="controls" autoplay width="100%" height="450px"></video>
      </el-dialog>

      <el-dialog title="在线频道" :visible.sync="rtcDialogVisible" width="60%" >
          <el-row :gutter="20">
              <el-col :span="12">
                  <div class="video-content">
                      <video ref="localVideo" width="80%" height="450px" playsinline autoplay></video>
                      <div style="line-height: 22px;font-size: 18px">本机视频</div>
                  </div>
              </el-col>
              <el-col :span="12">
                  <div class="video-content" >
                      <video ref="remoteVideo" width="80%" height="450px" playsinline autoplay></video>
                      <div style="line-height: 22px;font-size: 18px">对方视频</div>
                  </div>
              </el-col>
          </el-row>
      </el-dialog>

  </div>
</template>

<script>
import UcTable from "@/components/UcTable/index.vue";
import {deleteChannel, joinChannel, pullPerson} from "@/api/alirtc";
import {showVideoUser} from "@/api/user";


export default {
  name: "taskList",
  components: {UcTable},
  data(){
    return{
      searchForm:{
      },
        videoDialogVisible:false,
        videoUrl:'',
        rtcDialogVisible:false
    }
  },
  created() {
  },
  methods: {
      handleVideo(val){
          this.videoUrl = val.videoUrl
          this.videoDialogVisible = true
      },
      enterVideo(){
          //加入频道中

      },
      //校验当前设备是否支持
      isSupport(val,debug,channel){
          let option = {}
          let _this = this;
          if (debug){
              option.isDebug=true
          }
          val.isSupport(option).then((res)=>{
              this.onJoinEvent(val)
              this.onPublisher(val)
              this.onBye(val)
              this.onLeave(val)
              this.OnRefresh(val)
              this.startPreview(val)
              this.hasVideo = true;
              joinChannel({displayName:"消防队",channelId:channel.channel.substring(6),admin:false}).then(res=>{
                  console.log("joinChannel")
                  console.log(res.data)
                  _this.aliWebrtc.joinChannel(res.data,"消防队").then(obj=>{
                      _this.$nextTick(() => {
                          _this.publish(_this.aliWebrtc)
                          _this.startPreview(_this.aliWebrtc)
                      });
                      console.log("加入频道成功")
                  }).catch((error)=>{
                      console.log("加入频道失败",error)
                  })
              }).catch(error=>{
                  console.log("加入频道失败",error)
              })
          }).catch((error)=>{
              console.log("加入频道失败",error)
              this.$notify.error({
                  title: '成功',
                  message: "当前设备不支持webrtc"
              })
          })
      },
      //开启本地预览模式
      startPreview(val){
          val.startPreview(this.$refs.localVideo).then(()=>{
              console.log("本地预览")
          }).catch((error) => {
              console.log("预览失败",error)
          });
      },
      //推发布流
      publish(val){
          val.configLocalAudioPublish = true;
          val.configLocalCameraPublish = true;
          val.publish().then(()=>{
              console.log("发布流成功")
          } ,(error)=>{
              console.log("发布流失败",error);
          });
      },
      //加入视频通话
      joinChannel(val){
          this.aliWebrtc = new AliRtcEngine();
          this.isSupport(this.aliWebrtc,true,val)
      },
      // remote用户加入房间 onJoin
      onJoinEvent(val){
          val.on("onJoin", (publisher) => {
              console.log(publisher)
              val.configRemoteAudio(publisher.userId, true);
              val.configRemoteCameraTrack(publisher.userId, true, true);
              // showAlert(publisher.displayName + "加入房间","success");
              console.log(publisher.displayName + "加入房间");
          });
      },
      //remote流发布事件 onPublish
      onPublisher(val){
          val.on("onPublisher", (publisher) => {
              val.subscribe(publisher.userId).then((userId)=>{
                  console.log("userId")
                  console.log(userId)
                  console.log(this.remoteList)
                  console.log(this.$refs["remoteVideo"+(this.remoteList.length-1)])
                  this.$nextTick(() => {
                      val.setDisplayRemoteVideo(userId,this.$refs["remoteVideo"+(this.remoteList.length-1)],1)
                  });
              },(error)=>{
                  console.log(error.message);
              });
              let index = this.remoteList.indexOf(publisher);
              console.log(index)
              if (index === -1&&this.remoteList.length<8) {
                  //新增
                  this.remoteList.push(publisher)

              }
          });
      },
      //remote流结束发布事件 onUnPublisher
      onUnPublisher(val){
          val.on("onUnPublisher", (publisher) => {
              console.log("onUnPublisher",publisher);
              let index = this.remoteList.findIndex(function(item) {
                  return item.userId === publisher.userId;
              });
              console.log("index")
              console.log(index)
              this.remoteList.splice(index,1)
              if (this.remoteList.length<1){
                  this.leaveVideo()
              }
          });
      },
      // 被服务器踢出或者频道关闭时回调 onBye
      onBye(val){
          val.on("onBye",(message) =>{
              var msg;
              switch (message.code) {
                  case 1:
                      msg = "被服务器踢出";
                      break;
                  case 2:
                      msg = "频道关闭";
                      break;
                  case 3:
                      msg = "同一个ID在其他端登录,被服务器踢出";
                      break;
                  default:
                      msg = "onBye";
              }
              this.remoteList = []
          });
      },
      leaveVideo(){
          this.remoteList =[]
          this.aliWebrtc.leaveChannel();
          this.aliWebrtc.dispose();
          this.hasVideo = false;
      },
      /**
       * 检测到用户离开频道
       * 更新用户列表
       * 移除用户视图
       */
      onLeave(val){
          val.on("onLeave", (publisher) => {
              console.log(publisher);
              let index = this.remoteList.findIndex(function(item) {
                  return item.userId === publisher.userId;
              });
              console.log(index)
              this.remoteList.splice(index,1)
              if (this.remoteList.length<1){
                  this.leaveVideo()
              }
          })
      },
      //页面刷新时调用
      OnRefresh(val){
          window.onbeforeunload=function (e) {
              if (!val){
                  console.log("isSupport失败");
                  return ;
              }
              val.leaveChannel();
              val.dispose();
          }
      },
      beforeunloadHandler(){
          this.beforeUnloadTime=new Date().getTime();
      },
      unloadHandler(e){
          this.gapTime=new Date().getTime()-this.beforeUnloadTime;
          //判断是窗口关闭还是刷新
          if(this.gapTime<=5){//浏览器关闭
              //自己的操作行为
              let  actions = {"type":"offline","ucId":sessionStorage.getItem('ucId')};
              this.webSocketSend(JSON.stringify(actions));
              this.webSock.close() //离开路由之后断开websocket连接
          }
      },
      showVideoUser(){
          showVideoUser({customize:this.userId}).then(res=>{
              this.userList = res.data
          })
      },
      pullVideo(){
          this.videoForm.channelId = this.userId
          pullPerson(this.videoForm).then(res=>{
              console.log(res)
              this.videoForm = {}
              this.pullVideoStatus = false
          })
      },
      deleteChannel(){
          this.deleteForm.channelId = this.userId
          deleteChannel(this.deleteForm).then(res=>{
              console.log(res)
              this.deleteForm.channelId = {}
              this.resizeBox = false
              // this.unPublish(this.aliWebrtc)
              // this.stopPreview(this.aliWebrtc)
          })
      },
      unPublish(val){
          val.unPublish().then(()=>{
              console.log("结束流成功")
          } ,(error)=>{
              console.log("结束流失败",error);
          });
      },
      stopPreview(val){
          val.stopPreview().then(()=>{
              console.log("结束预览成功")
          }).catch((error) => {
              console.log("结束预览失败")
              // 结束预览失败
          });
      }
  }

}
</script>

<style scoped>

</style>